package com.apps.stoolkit;

import java.io.*;

/**
 * json工具类
 */

public class FileToolkit
{

    /**
     * 读取任意目录下文件，返回字符串
     * @param fileName
     * @return
     */
    public static String ReadFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从resource下加载文件
     * @param fileName
     * @return
     */
    public static String ReadResourceFile(String fileName) {
        String jsonStr = "";
        try {
            InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 创建文件
     * @param path
     * @param context
     */
    public static void WriteFile(String path,String fileName,String context)
    {
        try
        {
            File file=new File(path);
            if(!file.exists()) {//如果文件夹不存在
                file.mkdir();//创建文件夹
            }
            //打开文件流写入
            FileOutputStream out = new FileOutputStream(path+"\\"+fileName);
            PrintStream p = new PrintStream(out);
            p.println(context);
        }catch (Exception e)
        {

        }
    }
    public static void main(String... args) throws FileNotFoundException
    {

//        System.out.println(System.getProperty("user.dir").replaceAll("\\\\","/"));
          String context=ReadResourceFile("static/template/TemplateObject.java");
          WriteFile("d:/a","dsfdsfds.java",context);
    }
}
